package FenxiaoService

import (
	"context"
	"gdshop-font-api-go/app/request/FenxiaoReq"
	"gdshop-font-api-go/app/response/OrderResp"
	"gdshop-font-api-go/app/service/OrderBaseService"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
)

func getOrderListStatusWhere(status int) string {
	switch status {
	case 3:
		return " AND status = 10"
	case 2:
		return " AND status IN (90,99)"
	case 1:
		return " AND status = 1"
	default:
		return ""
	}
}

func OrderList(ctx context.Context, parames *FenxiaoReq.OrderList) *response.JsonResponse {
	dbPrefix := g.Cfg().GetString("database.prefix")
	where := g.Map{
		"delete_at < ?": 1,
		"id IN (SELECT order_id FROM " + dbPrefix +
			"fenxiao_order_details WHERE delete_at<1 AND member_id=?" + getOrderListStatusWhere(parames.Status) + ")": parames.MemberId,
	}

	jieguo, err := OrderBaseService.GetPager(ctx, where, parames.Page, parames.PageSize, 0, "")
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	memberId := int(parames.MemberId)
	// 处理分销信息
	jieguo, err = handleFenxiaoOrderInfo(ctx, memberId, jieguo)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessageData(nil, "成功", jieguo)
}

func handleFenxiaoOrderInfo(ctx context.Context, memberId int, jieguo *OrderResp.List) (*OrderResp.List, error) {
	orderIds := []int{}
	for _, item := range jieguo.List {
		orderIds = append(orderIds, item.Id)
	}
	rateMap := map[int]int{}
	array, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_order_details").Fields(
		"order_id,rate").Where(
		"member_id = ? AND order_id IN (?)", memberId, orderIds).All()
	if err != nil {
		return nil, err
	}

	// 取出订单ID和比例对应的比例
	for _, r := range array {
		rateMap[gconv.Int(r["order_id"])] = gconv.Int(r["rate"])
	}

	// 循环计算比例
	for _, item := range jieguo.List {
		item.Brokerage = float64(item.TotalPrice) / 100 * float64(rateMap[item.Id]) / 1000
	}

	return jieguo, nil
}

func OrderList2(ctx context.Context, parames *FenxiaoReq.OrderList) *response.JsonResponse {
	fields := []string{
		"fod.status AS fod_status",
		"fod.level_id AS fod_level_id",
		"os.goods_cover",
		"os.order_sub_no",
		"os.goods_name",
		"os.goods_option_title",
		"os.sell_price",
		"os.total",
		"os.paid",
		"(floor(os.paid * fod.rate / 1000000)) AS brokerage",
	}
	objDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_order_details").As("fod").
		Fields(fields).
		LeftJoin("order_sub os", "os.id = fod.order_sub_id")

	where := g.Map{
		"fod.member_id = ?": parames.MemberId,
	}

	if parames.Status > 0 {
		switch parames.Status {
		case 3:
			where["fod.status IN (?)"] = []int{10, 90}
			break
		case 2:
			where["fod.status"] = 99
			break
		case 1:
			where["fod.status"] = 1
			break
		default:
			break
		}
	}

	all, err := objDb.Order("os.id DESC").Page(parames.Page, parames.PageSize).
		Where(where).All()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	count, err := objDb.Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessageData(nil, "成功", g.Map{
		"page_info": tools.GetPageInfo(count, parames.Page, parames.PageSize),
		"list":      all,
		"status_text": g.Map{
			"0":  "交易关闭",
			"1":  "待结算",
			"10": "已退款",
			"90": "待结算",
			"99": "已结算",
		},
		"photo_base_url": g.Cfg().GetString("site.PhotoUrlProfix"),
	})
}
